package com.sc.nft.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.MallActivityShareTeamDao;
import com.sc.nft.dao.StaticDataDao;
import com.sc.nft.dao.UserCollectionDao;
import com.sc.nft.entity.MallActivityShare;
import com.sc.nft.entity.MallActivityShareTeam;
import com.sc.nft.entity.StaticData;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.entity.dto.*;
import com.sc.nft.entity.vo.AdminMallActivityShareTeamPageVO;
import com.sc.nft.entity.vo.MallActivityShareTeamPageVO;
import com.sc.nft.enums.ShareTeamStatusEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.MallActivityShareService;
import com.sc.nft.service.MallActivityShareTeamService;
import com.sc.nft.service.MallShareTeamOrderService;
import com.sc.nft.sup.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 分享购团队信息 服务实现类
 * </p>
 *
 * @author ligen
 * @since 2023-12-13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MallActivityShareTeamServiceImpl implements MallActivityShareTeamService {

    private final MallActivityShareTeamDao mallActivityShareTeamDao;
    private final UserCollectionDao userCollectionDao;
    private final StaticDataDao staticDataDao;
    @Autowired
    MallActivityShareService mallActivityShareService;

    /**
     * 分享成团列表
     *
     * @param adminMallActivityShareTeamPageVO
     * @return
     */
    @Override
    public Page<AdminMallActivityShareTeamPageDTO> getAdminMallActivityShareTeamPageDTO(AdminMallActivityShareTeamPageVO adminMallActivityShareTeamPageVO) {
        return mallActivityShareTeamDao.getAdminMallActivityShareTeamPageDTO(adminMallActivityShareTeamPageVO.getPageNo(), adminMallActivityShareTeamPageVO.getPageSize(), adminMallActivityShareTeamPageVO.getStatus(), adminMallActivityShareTeamPageVO.getActivityShareId());
    }

    /**
     * 用户端分享成团列表
     *
     * @param userInfo
     * @param mallActivityShareTeamPageVO
     * @return
     */
    @Override
    public Page<MallActivityShareTeamPageDTO> getMallActivityShareTeamPageDTO(UserInfo userInfo, MallActivityShareTeamPageVO mallActivityShareTeamPageVO) {
        Page<MallActivityShareTeamPageDTO> mallActivityShareTeamPageDTO = mallActivityShareTeamDao.getMallActivityShareTeamPageDTO(mallActivityShareTeamPageVO.getPageNo(), mallActivityShareTeamPageVO.getPageSize(), userInfo.getId());
        for (MallActivityShareTeamPageDTO record : mallActivityShareTeamPageDTO.getRecords()) {
            if (StrUtil.isNotBlank(record.getCoverImage())) {
                record.setCoverImage(StrUtil.split(record.getCoverImage(), ",").get(0));
            }
        }
        return mallActivityShareTeamPageDTO;
    }

    /**
     * 用户成团详情
     *
     * @param userInfo
     * @param teamId
     * @return
     */
    @Override
    public MallActivityShareTeamDetailDTO getMallActivityShareTeamDetailDTO(UserInfo userInfo, Long teamId) {
        MallActivityShareTeamDetailDTO mallActivityShareTeamDetailDTO = mallActivityShareTeamDao.getMallActivityShareTeamDetailDTO(userInfo.getId(), teamId);
        if (StrUtil.isNotBlank(mallActivityShareTeamDetailDTO.getCoverImage())) {
            mallActivityShareTeamDetailDTO.setCoverImage(StrUtil.split(mallActivityShareTeamDetailDTO.getCoverImage(), ",").get(0));
        }
        // 分享链接
        StaticData staticData = staticDataDao.getByType("app_share_link");
        String shareLink = staticData.getValue() + userInfo.getInviteCode() + "&shareTeamId=" + mallActivityShareTeamDetailDTO.getId() + "&id=" + mallActivityShareTeamDetailDTO.getActivityShareId();
        mallActivityShareTeamDetailDTO.setShareLink(shareLink);
        return mallActivityShareTeamDetailDTO;
    }

    /**
     * 获取分享团队弹窗信息
     *
     * @param teamId
     * @return
     */
    @Override
    public ActivityShareTeamPopUpDetailDTO getActivityShareTeamPopUpDetailDTO(Long teamId) {
        ActivityShareTeamPopUpDetailDTO activityShareTeamPopUpDetailDTO = mallActivityShareTeamDao.getActivityShareTeamPopUpDetailDTO(teamId);
        if (StrUtil.isNotBlank(activityShareTeamPopUpDetailDTO.getCoverImage())) {
            activityShareTeamPopUpDetailDTO.setCoverImage(StrUtil.split(activityShareTeamPopUpDetailDTO.getCoverImage(), ",").get(0));
        }
        return activityShareTeamPopUpDetailDTO;
    }

    /**
     * 是否已开团
     *
     * @param userId
     * @param activityShareId
     * @return
     */
    @Override
    public MallActivityShareTeam hasShareTeamDetail(Long userId, Long activityShareId) {
        return mallActivityShareTeamDao.hasShareTeamDetail(userId, activityShareId);
    }

    /**
     * 用户开团
     *
     * @param userInfo
     * @param activityShareId
     * @return
     */
    @Override
    public MallActivityShareTeamDetailDTO userStartShareTeam(UserInfo userInfo, Long activityShareId) {
        Date now = DateTime.now();
        // 获取分享购活动
        MallActivityShare mallActivityShare = mallActivityShareService.getById(activityShareId);
        if (!mallActivityShare.getStatus()) {
            throw new GlobalRunTimeException("活动已下架");
        }
        // 判断是否需要nft进行开团
        if (Objects.nonNull(mallActivityShare.getCollectionId())) {
            // 校验
            Integer count = userCollectionDao.getByUserIdAndCollectionIdCount(userInfo.getId(), mallActivityShare.getCollectionId());
            if (NumberUtil.isGreater(BigDecimal.valueOf(1), new BigDecimal(count))) {
                throw new GlobalRunTimeException("不满足开团条件");
            }
        }
        MallActivityShareTeam activityShareTeam = hasShareTeamDetail(userInfo.getId(), activityShareId);
        if (Objects.nonNull(activityShareTeam)) {
            throw new GlobalRunTimeException("您已经开团");
        }
        MallActivityShareTeam mallActivityShareTeam = new MallActivityShareTeam();
        mallActivityShareTeam.setActivityShareId(activityShareId);
        mallActivityShareTeam.setUserId(userInfo.getId());
        mallActivityShareTeam.setUserTel(userInfo.getUserTel());
        mallActivityShareTeam.setTotalOrderNum(0);
        mallActivityShareTeam.setValidOrderNum(0);
        // 开始时间
        mallActivityShareTeam.setStartTime(now);
        DateTime endTime = DateUtil.offsetMinute(now, mallActivityShare.getValidMinute());
        mallActivityShareTeam.setEndTime(endTime);
        mallActivityShareTeam.setStatus(ShareTeamStatusEnum.GROUPING_IN_PROGRESS);
        mallActivityShareTeam.setIsIssue(Boolean.FALSE);
        mallActivityShareTeam.setIsCanIssue(Boolean.FALSE);
        mallActivityShareTeam.insert();
        MallActivityShareTeamDetailDTO mallActivityShareTeamDetailDTO = getMallActivityShareTeamDetailDTO(userInfo, mallActivityShareTeam.getId());
        return mallActivityShareTeamDetailDTO;
    }

    /**
     * 获取用户开团
     *
     * @param id
     * @return
     */
    @Override
    public MallActivityShareTeam getById(Long id) {
        MallActivityShareTeam activityShareTeam = mallActivityShareTeamDao.getById(id);
        Assert.notNull(activityShareTeam, () -> new GlobalRunTimeException(ErrorCode.SHARE_BUYING_ACTIVITY_TEAM_DOES_NOT_EXIST));
        return activityShareTeam;
    }

    /**
     * 获取分享购的团队
     *
     * @param activityShareId
     * @return
     */
    @Override
    public List<MallActivityShareTeam> getListByActivityShareId(Long activityShareId, ShareTeamStatusEnum status) {
        return mallActivityShareTeamDao.getListByActivityShareId(activityShareId, status);
    }

    /**
     * 修改拼团状态
     * 状态：拼团中 -> 拼团成功 拼团中 -> 拼团失败 拼团成功 -> 拼团失败
     *
     * @param id     成团ID
     * @param status 成团状态
     * @return
     */
    @Override
    public Boolean updateStatus(Long id, ShareTeamStatusEnum status) {
        Boolean isUpdate = false;
        Boolean isCanUpdate = false;
        MallActivityShareTeam mallActivityShareTeam = getById(id);
        if (ShareTeamStatusEnum.GROUP_SUCCESSFULLY == status && mallActivityShareTeam.getStatus() == ShareTeamStatusEnum.GROUPING_IN_PROGRESS) {
            // 拼团成功
            isCanUpdate = true;
        } else if (ShareTeamStatusEnum.GROUPING_FAILURE == status && (mallActivityShareTeam.getStatus() == ShareTeamStatusEnum.GROUPING_IN_PROGRESS || mallActivityShareTeam.getStatus() == ShareTeamStatusEnum.GROUP_SUCCESSFULLY)) {
            // 拼团失败
            isCanUpdate = true;
        }
        if (isCanUpdate) {
            mallActivityShareTeamDao.updateStatus(mallActivityShareTeam.getId(), status);
            isUpdate = true;
        }
        return isUpdate;
    }

    /**
     * 修改成团是是否可以发放收益
     *
     * @param id
     * @param isCanIssue
     * @return
     */
    @Override
    public Boolean updateIsCanIssue(Long id, Boolean isCanIssue, Boolean updateEndTime) {
        return mallActivityShareTeamDao.updateIsCanIssue(id, isCanIssue, updateEndTime);
    }

    /**
     * 添加成团订单数量
     *
     * @param id
     * @return
     */
    @Override
    public Boolean addOrderNumById(Long id, Integer count) {
        Boolean addOrderNum = mallActivityShareTeamDao.addOrderNumById(id, count);
        MallActivityShareTeam mallActivityShareTeam = getById(id);
        MallActivityShare mallActivityShare = mallActivityShareService.getById(mallActivityShareTeam.getActivityShareId());
        if (mallActivityShare.getMinOrderNum() <= mallActivityShareTeam.getValidOrderNum()) {
            updateIsCanIssue(id, Boolean.TRUE, Boolean.FALSE);
        }
        return addOrderNum;
    }

    /**
     * 减少有效订单数量
     *
     * @param id
     * @return
     */
    @Override
    public Boolean subValidOrderNumById(Long id, Integer count) {
        Boolean subValidOrderNum = mallActivityShareTeamDao.subValidOrderNumById(id, count);
        MallActivityShareTeam mallActivityShareTeam = getById(id);
        MallActivityShare mallActivityShare = mallActivityShareService.getById(mallActivityShareTeam.getActivityShareId());
        if (mallActivityShare.getMinOrderNum() > mallActivityShareTeam.getValidOrderNum()) {
            updateIsCanIssue(id, Boolean.FALSE, Boolean.FALSE);
        }
        return subValidOrderNum;
    }

    /**
     * 获取上下架分享购的拼团中团队列表
     *
     * @return
     */
    @Override
    public List<MallActivityShareTeam> getListByShareStatus() {
        return mallActivityShareTeamDao.getListByShareStatus();
    }
}
